define(function (require, exports, module) {
    require('authorize');
    require('permission');
    var $ = require('jquery');
    var util = require('util');
    var ui = require('ui');
    var angular = require("angular");
    var dialog = require("dialog");
    var environment = require('environment');
    require("angular-interceptor");
    require("angular-ui");
    require("angular-messages");
    require("jqtree");
    require("placeholder");
    require("/public/js/service/public_no/service");
    require("/static_public/js/angular_directive/clipboard");
    require("/public/js/service/add_application/select_project");
    require('global');

    var api_prefix = G_CONFIG["api_prefix"]; //api前缀

    var wechatAuth = {
        /**
         * @param {function(Object)} callback
         */
        init: function (callback) {
            var self = this;
            var wxRedirectUrl = environment.wx + '/index.php?r=third-auth/redirect-auth&' + $.param({
                    url: 'http://' + location.host + '/page/auth/wechat_redirect.shtml'
                });

            var $wnd = this.$wnd = $(window);
            var $iframe = this.$iframe = $('<iframe frameborder="0">')
                .css({
                    background: 'url("/static_public/images/loading.gif") no-repeat center center'
                });

            var $body = this.$body = $('body');
            this.bodyOverFlowY = $body.css('overflowY');

            this.$closeBtn = $('<span style="width:60px;height:60px;cursor:pointer;background:url(http://img-dev.myscrmimg.cn/projects/qmyx/public/images/icon/icon_close.png) no-repeat center center"></span>')
                .css({position: 'fixed', top: 5, right: 15, zIndex: 1001});

            this.resizeHandler = function () {
                $iframe
                    .css({
                        width: $wnd.width(),
                        height: $wnd.height()
                    })
            };

            $iframe
                .css({
                    position: 'fixed',
                    top: 0,
                    left: 0,
                    zIndex: 1000,
                    width: $wnd.width(),
                    height: $wnd.height()
                })
                .attr('src', wxRedirectUrl);

            /**
             * 更新微信公众号登录用户信息，供微信回调内嵌iframe调用
             * @param authInfo
             */
            window.updateAuthInfo = function (authInfo) {
                callback && callback(authInfo);
                self.close();
            };
        },
        /**
         * 关闭授权界面
         */
        close: function () {
            this.$iframe.remove();
            this.$closeBtn.remove().off('click');
            this.$body.css('overflowY', this.bodyOverFlowY);
            this.$wnd.off('resize', this.resizeHandler)
        },
        /**
         * 展示授权界面
         */
        show: function () {
            var $iframe = this.$iframe;
            var $closeBtn = this.$closeBtn;
            var $body = this.$body;
            var self = this;
            var $wnd = this.$wnd;

            $body.css('overflowY', 'hidden');
            $wnd.off('resize', this.resizeHandler).on('resize', this.resizeHandler);
            $iframe
                .css({
                    width: $wnd.width(),
                    height: $wnd.height()
                })
                .appendTo($body)

            $closeBtn
                .off('click')
                .on('click', function () {
                    self.close();
                })
                .appendTo($body);
        }
    };

    angular.module('setPublic', ['ngMessages', 'ngUI', 'ngInterceptor', 'angular.directive.clipboard', 'selectProjectSrv', 'publicNoService', 'ngPlaceholder'])
        .controller('GzhAddInfoController', ['$scope', '$http', 'commonService', 'projService',
            function ($scope, $http, commonService, projService) {
                function fixedData(data) {
                    angular.forEach(data, function (item) {
                        item.children = item.childNodes;
                        fixedData(item.childNodes);
                    });
                    return data;
                }

                function getOrgTree(){
                    var containerId = $scope.optType === 'add' ? '#add-gzh' : '#update-gzh';
                    return $(containerId).find('#tree_table');
                }

                //所属组织
                commonService.queryAllOrganizations().then(function (res) {
                    if (res && res.data && res.data.retCode == 0) {
                        getOrgTree().tree({
                            data: fixedData(res.data.data),
                            dragAndDrop: false,
                            useContextMenu: false,
                            autoOpen: 0, //展开级别
                            onCreateLi: function (node, $li) {
                            },
                            //是否可以移动
                            onCanMove: function (node) {
                                return false;
                            },
                            //是否可以移动到
                            onCanMoveTo: function (moved_node, target_node, position) {
                                //只能在同级节点中移动
                                return false;
                            },
                            //移动句柄
                            onIsMoveHandle: function ($ele) {
                                return false;
                            }
                        }).on(
                            'tree.click',
                            function (event) {
                                var node = event.node;

                                $scope.belongsOrganization = node;
                                $scope.isTreeCollapse = false;
                                $scope.$apply();
                            }
                        );
                    }
                });

                $scope.optType = location.search.indexOf('type=update') !== -1 ? 'update' : 'add';


                $scope.getTree = function () {

                };
                $scope.isTreeCollapse = false;

                $scope.toggleTreeCombo = function () {
                    $scope.isTreeCollapse = !$scope.isTreeCollapse;
                    var clickWindow = function (event) {
                        var target = $(event.target);
                        if (getOrgTree().parent().has(target).length < 1) {
                            if ($scope.isTreeCollapse) {
                                $scope.isTreeCollapse = false;
                                $scope.$apply();

                                $(window).off('click', clickWindow);
                            }
                        }
                    };
                    $(window).on('click', clickWindow);
                };

                $scope.winXinType = {
                    typeList: [
                        {value: '', text: '请选择微信号类型'},
                        {value: '1', text: '订阅号'},
                        {value: '2', text: '微信老帐号升级后的订阅号'},
                        {value: '3', text: '服务号'}
                    ]
                };

                $scope.data = {
                    winxintype: ''
                };

                wechatAuth.init(function (authInfo) {
                    if (authInfo && !authInfo['errmsg']) {
                        var data = $scope.data;
                        for (var key in authInfo) {
                            if (authInfo.hasOwnProperty(key)) {
                                data[key] = authInfo[key];

                                if (key === 'winxintype') {
                                    data[key] = parseInt(data[key]) + 1 + '';
                                }
                            }
                        }

                        $scope.$applyAsync();
                    } else {
                        //绑定失败
                        ui.showErrTip(authInfo['errmsg']);
                    }
                });
                $scope.read_flag = false;

                /**
                 * 跳转微信登录页面
                 */
                $scope.redirectWechatAuth = function () {
                    if($scope.read_flag){
                        wechatAuth.show();
                    }else{
                        $scope.read_flag_tip = true;
                    }
                };

                //下一步
                $scope.cur_step = 1;
                $scope.prevStep = function () {
                    $scope.cur_step--;
                };

                $scope.nextStep = function (formValid) {
                    switch ($scope.cur_step) {
                        case 1:
                            //触发FORM表单验证
                            setTimeout(function () {
                                $("#first_step_next")[0].click();
                            }, 0);

                            $scope.read_flag_tip = !$scope.read_flag;

                            if (!formValid) {
                                return;
                            } else {
                                var data = $scope.data;
                                commonService.postStepOneData({
                                    buguid: $scope.belongsOrganization.id,
                                    wxname: data.wxname,
                                    wxid: data.wxid,
                                    weixin: data.weixin,
                                    winxintype: data.winxintype,
                                    appid: data.appid,
                                    appsecret: data.appsecret,
                                    is_third_auth: '1'
                                })
                                    .success(function (res) {
                                        var retCode = res.retCode;
                                        if (retCode == 0) {
                                            $scope.cur_step++;
                                        } else {
                                            ui.showErrTip(res.data.errMsg);
                                        }
                                    })
                                    .error(function () {
                                        ui.showErrTip();
                                    })
                            }
                            break;
                        case 2:
                            $scope.cur_step++;
                            break;
                    }
                };

                $scope.save = function () {
                    var postData = [];
                    var stepThreeData = $scope.stepThreeData || [];
                    for(var i =0;i< stepThreeData.length;i++){
                        var app = stepThreeData[i];
                        var projList = app.list;
                        for (var j = 0;j < projList.length ; j++) {
                            postData.push({
                                'ApplicationId': app.id,
                                'ApplicationCode': app.appcode,
                                'ProjectId': projList[j].id
                            });
                        }
                    }
                    commonService.save({appProjBinds: postData})
                        .then(function (res) {
                            if (res.data.retCode == 0) {

                                var cannotMsg = function (arr) {
                                    var msg = '', projArr = [];
                                    for (var i = 0, len = arr.length; i < len; i++) {
                                        projArr.push(arr[i].ProjectName);
                                    }
                                    msg = projArr.join("、");
                                    return msg;
                                };

                                var hasBusinessData = res.data.data.hasbusinessdata && res.data.data.hasbusinessdata.length > 0;
                                var cannotAddData = res.data.data.cannotadddata && res.data.data.cannotadddata.length > 0;

                                if (hasBusinessData || cannotAddData) {
                                    var msg = '';

                                    if (hasBusinessData) {
                                        var deleteMsg = cannotMsg(res.data.data.hasbusinessdata);
                                        msg += '<div><span class="c-orange">' + deleteMsg + ' </span>已产生业务数据，无法删除。</div>';
                                    }

                                    if (cannotAddData) {
                                        if(hasBusinessData){
                                            msg += '<div style="border-top: 1px dashed #ccc; margin: 8px 0;"></div>';
                                        }
                                        var deleteMsg = cannotMsg(res.data.data.cannotadddata);
                                        var noWcbPhone = _.filter(res.data.data.cannotadddata, function (item) {
                                            return item.ApplicationCode == '5030' && item.flag;//项目没有绑定旺财宝话机
                                        });
                                        if(noWcbPhone.length>0){
                                            var noWcbPhoneMsg = cannotMsg(noWcbPhone);
                                            msg+='<div><span class="c-orange">' + noWcbPhoneMsg + ' </span>项目没有绑定旺财宝话机</div>';
                                        }
                                        msg += '<div><span class="c-orange">' + deleteMsg + ' </span>项目绑定出现异常，请联系云客运营400QQ客服：4008333870</div>';
                                    }
                                    util.alert(msg);

                                } else {
                                    util.alert('添加公众号成功', {
                                        ok: function () {
                                            location.href = '/';
                                        }
                                    });
                                }
                            }
                        });
                };

                $scope.updateSave = function () {
                    var data = $scope.data;
                    commonService.saveInEdit({
                        buguid: $scope.belongsOrganization.id,
                        wxname: data.wxname,
                        wxid: data.wxid,
                        weixin: data.weixin,
                        winxintype: data.winxintype,
                        appid: data.appid,
                        appsecret: data.appsecret,
                        is_third_auth: data.is_third_auth
                    })
                        .then(function (res) {
                            if (res.data.retCode == 0) {
                                ui.showSucTip();
                                location.href = '/';
                            }
                        });
                };

                $scope.cancel = function () {
                    location.href = '/';
                };

                $scope.selectProjDialog = function (appItem, dialog, dialogScope) {
                    projService.selectProjDialog(appItem, dialog, dialogScope);
                };

                $scope.selectProjDialog = function (appItem, dialog, dialogScope) {
                    projService.selectProjDialog(appItem, dialog, dialogScope);
                };

                $scope.saveSelect = function (data) {
                    projService.confirm(data,function(){
                        $scope.$applyAsync();
                    });
                };

                $scope.deleteProject = function (projectItem, projs) {
                    util.removeFromArr(projectItem, projs);
                };

                $scope.$watch('cur_step', function () {
                    switch ($scope.cur_step) {
                        case 2:
                            commonService.getStepTwoData().then(function (res) {
                                var retCode = res.data.retCode;
                                if (retCode == 0) {
                                    $scope.stepTwoData = res.data.data;
                                }
                            });
                            break;
                        case 3:
                            if (!$scope.stepThreeData) {
                                commonService.getStepThreeData().then(function (res) {
                                    var retCode = res.data.retCode;
                                    if (retCode == 0) {
                                        $scope.stepThreeData = res.data.data;
                                    }
                                });
                            }
                            break;
                    }
                });

                $scope.afterCopy = function(){
                    ui.showSucTip('复制成功');
                };
            }]);

    angular.bootstrap(document, ['setPublic']);
});